package com.ctg.itrdc.sysmgr.portal.service.utils;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.ctg.itrdc.sysmgr.portal.service.exception.SysmgrServiceException;
import com.google.common.collect.Lists;

public class BeanUtils extends org.apache.commons.beanutils.BeanUtils {

	public static void applyIfNotException(Object target, Object source) {
		notNull(target);
		notNull(source);
		try {
			org.springframework.beans.BeanUtils.copyProperties(source, target);
//			applyIf(target, source);// 顺序目标,源
		} catch (Exception e) {
			throw new SysmgrServiceException("拷贝出错了~", e.getCause());
		}
	}
	
	public static <T> T applyIfNotException(Object source,Class<T> destClass){
		notNull(source);
		try {
			T target = destClass.newInstance();
			applyIfNotException(target,source);
//			applyIf(target, source);// 顺序目标,源
			return target;
		} catch (Exception e) {
			throw new SysmgrServiceException("拷贝出错了~", e.getCause());
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> copyListNotException(
			@SuppressWarnings("rawtypes") List sourceList, Class<T> destClass) {
//		notNull(sourceList);
		if(CollectionUtils.isEmpty(sourceList)){
			return Lists.newArrayList();
		}
		try {
//			return copyList(sourceList, destClass);
			List<T> list = new ArrayList<T>();
			if (sourceList != null && sourceList.size() > 0) {
				for (Object obj : sourceList) {
					Object dest = destClass.newInstance();
					applyIfNotException(dest, obj);
					list.add((T) dest);
				}
			}
			return list;
		} catch (Exception e) {
			throw new SysmgrServiceException("拷贝出错了~", e.getCause());
		}

	}
	
	public static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz){
		return org.springframework.beans.BeanUtils.getPropertyDescriptors(clazz);
	}
	
	public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz,String propertyName){
		return org.springframework.beans.BeanUtils.getPropertyDescriptor(clazz, propertyName);
	}

	private static void notNull(Object target) {

		if (target == null || target.equals(null)) {
			throw new SysmgrServiceException("對象不能為空~");
		}
	}
	
	private static void notNull(Collection<?> c){
		if(c==null || c.equals(null) || c.size()<=0){
			throw new SysmgrServiceException("集合不能為空~");
		}
	}
}
